import React, { useState } from 'react'
import { useQuery } from 'react-query'
import { PlanetPages } from '../types'
import { Planet } from './Planet'

const fetchPlanets = async (page: number): Promise<PlanetPages> => {
  const res = await fetch(`http://swapi.dev/api/planets/?page=${page}`)
  return res.json()
}

const Planets = () => {
  const [page, setPage] = useState<number>(1)
  const { data, isLoading, isError, isSuccess, isFetching } = useQuery<PlanetPages>(
    ['planets', page] as const,
    () => fetchPlanets(page),
    {
      keepPreviousData: true // 用作分页时，取消loading状态，保存之前的数据视图
    }
  )
  return (
    <div>
      <h2>Planets</h2>
      {isError && <div>Error Fetching Data</div>}
      {isLoading && <div>Loading Data</div>}
      {isSuccess && (
        <>
          <button disabled={!data?.previous} onClick={() => !isFetching && setPage(page - 1)}>
            prev
          </button>
          <span>{page}</span>
          <button disabled={!data?.next} onClick={() => !isFetching && setPage(page + 1)}>
            next
          </button>
          <div>
            {data?.results.map((planet) => (
              <Planet key={planet.name} planet={planet} />
            ))}
          </div>
        </>
      )}
    </div>
  )
}

export default Planets
